<?php
/**
 * 房型介绍相关，包括搜索处理
 *
 * @author Mike
 */
class HouseAction extends CommonAction {
     public function index(){
        $id = $_GET['id'];
        $house = $this->getHouseDetail($id);
        $hotel = M('Hotel')->where('id ='.$house['hotel_id'])->find();
        $this -> assign('house',$house);
        $this -> assign('hotel', $hotel);
        $con = array(
            'id' => array('neq',$id),
            'hotel_id' => $house['hotel_id'],
        );
        $this->assign('houseList',M('House')->where($con)->getField('id,name'));
        $this->assign('hotelList',M('Hotel')->where('status = 1 and id !='.$house['hotel_id'])->order('sort')->getField('id,name'));
        $map = array(
            'status' => 1,//应该是approvedTODO
            'pid' => $_GET['id'],
            'type' => 0,
        );
        $message = M('Comment') ->where($map)->order('create_time desc')->findAll();
        $this->assign('message',$message);
        $this->assign('bdmap',1);
        //SEO
        $house_title = $house['name'].'-'.$hotel['address'].'-'.getConfigVal($house['layout'],'layout').'-最低'.$house['price']['default'].'元/天';
        $meta_title = empty($house['meta_title']) ? $house_title : $house['meta_title'];
        $this->assign('title',$meta_title);
        $meta_description = empty($house['meta_description']) ? cutstr( getDesc($house['description']),400 ) : $house['meta_description'];
        $this->assign('desc',$meta_description );
        $this->assign('keywords',$house['meta_keywords']);

        $this->display();
    }

        /**
     * @param <type> $id hotel id
     */
    protected function getHouseDetail($id){
        $map = array(
            'status' => 1,
            'id' => intval($id),
        );
        $data = M('House')->where($map)->find();
        if(is_array($data) ){
            $data['logo'] = $this->get_picture($id,'house',2);
            $data['pic'] = $this->get_picture($id,'house',1); //得到所有的附属图片
            $data['price'] = $this->getPrice($id);//获取所有的价格，包括默认最小价格
        }
        return $data;
    }

    /**
     * 预订房型
     */
    public function book(){
        
        $member = $_SESSION[C('USER_AUTH_KEY')];
        if(!isset($member)){
            //setcookie("returnUrl",$_SERVER['PHP_SELF'] ,0,'/', $_SERVER['SERVER_NAME']);
            setcookie("returnUrl",$_SERVER['PHP_SELF'],0,'/');
            $this->assign('jumpUrl', __APP__.'/Index/login/');
            $this->error('请先登录！',false,3);
        }
        $this->display();
    }

    public function orderCreate(){
        $data = $_POST;
        $data['member_id'] = $_SESSION[C('USER_AUTH_KEY')];
        $data['totalprice'] = $this->getTotalPrice($_POST['house_id'], $_POST['room_num'], $_POST['start_time'], $_POST['end_time']);
        if($data['totalprice'] == 0){
            $this->error("订单总价有问题，请返回重新预订");
        }else if(empty($_POST['room_num'])){
			 $this->error("请填写入住房间数！");
		}
		else if(empty($_POST['person_num'])){
			 $this->error("请填写入住人数！");
		}
		else if(empty($_POST['start_time'])){
			 $this->error("请填写入住时间！");
		}
		else if(empty($_POST['end_time'])){
			 $this->error("请填写离开时间！");
		}
        $data['totalprice'] = 0;
        $data['start_time'] = strtotime($_POST['start_time']);
        $data['end_time'] = strtotime($_POST['end_time']);
        $data['status'] = 1;
        $data['create_time'] = time();
        $data['order_no'] = $this->genManNo();
        $Order = D('Order');
        if(false == $stat = $Order->create()){
            $this ->error($Order->getError);
        }
        if(0 != $orderId = $Order->add($data)){
            $this -> assign('jumpUrl',__APP__.'/Member/index/entry/order');
            $msg = '上海好家服务公寓有新预订单'.$data['order_no'].',姓名：'.getModelName($data['member_id'], 'Member').",房型：".getModelName($_POST['house_id'],"House").',入住：'.$_POST['start_time'].",离开：".$_POST['end_time'];
            //sendMsg($msg);
            $alert_value = M('Configure')->where('var_name = "alert_type" ')->getField('value');
            if ($alert_value == 1) {
                sendMail("上海好家服务公寓提醒信息", $msg, "上海好家服务公寓<info@okhome.cn>", 'lm@okhome.cn');
            }
            $this->success('恭喜您，您的房间已经预订成功！我们将尽快与您联系！',false,10);
        }
        else{
            $this ->error('对不起，预订失败，请重新预订或联系我们！');
        }
    }

    /*
     * 顶部菜单搜索
     */
    public function search(){
        //TODO暂不分页
        $district = intval($_REQUEST['district']);
        $layout =  intval($_REQUEST['layout']);
        $price =  intval($_REQUEST['price']);
        $map = array();
        if($district != -1){
            $map['district'] = $district;
        }
        if($layout != -1){
            $map['layout'] = $layout;
        }
        if($price == 260){
            $map['price'] = array('lt',260);
        }
        if($price == 400){
            $map['price'] = array('between','260,400');
        }
         if($price == 401){
            $map['price'] = array('egt',401);
        }
        $map['status'] = 1;
        $map['attachfunc'] = 2;
        $HouseView = D('HouseView');
        $result = $HouseView ->where($map)->field('id,name,hname,url,price,district,address,layout,start_day,end_day,description')->group('id')->findAll();
        $this->assign('result',$result);
        $this->assign('hotelList',M('Hotel')->where('status = 1 ')->order('sort')->getField('id,name'));//推荐公寓
        $this->assign('title','上海'.getConfigVal($district, 'district').' - '.getConfigVal($layout, 'layout').' - 价格低于'.$price.' 元/日的酒店式公寓推荐'  );
        $this->assign('desc',cutstr( getDesc($result[0]['name'].' '.$result[0]['description']) ),400 ) ;
        $this->display();
    }

        /**type=0预订单，1为入住单
     *生成单号如 20110528-001 ，前几位为当前单子的日期，后三位自动增长
     */
    protected function genManNo($type=0){
        $currday = date('Ymd');
        $model = '';
        if($type == 0) { //生成预订单号YD20110530-001
            $model = M('Order');
            $lastNo = $model ->order('id desc')->field('order_no')->find();
            $value = explode('-',$lastNo['order_no'] );
            if(empty($value)){
               return $no = 'YD'.$currday.'-001';
            }
            else{
                if( substr($value['0'],2) == $currday){
                    $value['1'] += 1;
                     $value['1'] = sprintf("%03d", $value['1'] ); //格式化为001
                }
                else{
                    $value['1'] = '001';
                }
                return $no = 'YD'.$currday.'-'.$value['1'];
            }
        }
        elseif($type == 1) {  //生成入住单号 20110528-001
            $model = M('Checkin');
            $lastNo = $model ->order('id desc')->field('checkin_no')->find();
            $value = explode('-',$lastNo['checkin_no'] );
            if(empty($value)){
               return $no = $currday.'-001';
            }
            else{
                if($value['0'] == $currday){
                    $value['1'] += 1;
                     $value['1'] = sprintf("%03d", $value['1'] ); //格式化为001
                }
                else{
                    $value['1'] = '001';
                }
                return $no = $currday.'-'.$value['1'];
            }
        }
    }

}
?>
